<?php

// 应用公共文件

use app\common\service\NodeService;
use think\Request;
use app\common\service\AuthService;
use think\facade\Cache;
use think\Db;

if (!function_exists('check_login')) {

    /**
     * 检测前端用户是否登录
     */
    function check_login() {
        if (empty(session('user'))) {
            return false;
        } else {
            return true;
        }
    }
}

if (!function_exists('auth')) {

    /**
     * 权限节点判断
     * @param $node 节点
     * @return bool （true：有权限，false：无权限）
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function auth($node) {
        return AuthService::checkNode($node);
    }
}

if (!function_exists('parseNodeStr')) {

    /**
     * 驼峰转下划线规则
     * @param string $node
     * @return string
     */
    function parseNodeStr($node) {
        $tmp = [];
        foreach (explode('/', $node) as $name) {
            $tmp[] = strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
        }
        return str_replace('._', '.', trim(join('/', $tmp), '/'));
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value) {
        $value = sha1('ytwl_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('__buildData')) {

    /**
     * 构建数据
     * @param $data   模型数据
     * @param $method 模型方法
     */
    function __buildData(&$data, $method) {
        foreach ($data as &$vo) {
            $vo->$method;
        }
    }
}

if (!function_exists('alert')) {

    /**
     * 弹出层提示
     * @param string $msg  提示信息
     * @param string $url  跳转链接
     * @param int    $time 停留时间 默认2秒
     * @param int    $icon 提示图标
     * @return string
     */
    function alert($msg = '', $url = '', $time = 3, $icon = 6) {
        $success = '<meta name="renderer" content="webkit">';
        $success .= '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">';
        $success .= '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">';
        $success .= '<script type="text/javascript" src="/static/plugs/jquery/jquery-2.2.4.min.js"></script>';
        $success .= '<script type="text/javascript" src="/static/plugs/layui-layer/layer.js"></script>';
        if (empty($url)) {
            $success .= '<script>$(function(){layer.msg("' . $msg . '", {icon: ' . $icon . ', time: ' . ($time * 1000) . '});})</script>';
        } else {
            $success .= '<script>$(function(){layer.msg("' . $msg . '",{icon:' . $icon . ',time:' . ($time * 1000) . '});setTimeout(function(){self.location.href="' . $url . '"},2000)});</script>';
        }
        return $success;
    }
}

if (!function_exists('msg_success')) {

    /**
     * 成功时弹出层提示信息
     * @param string $msg  提示信息
     * @param string $url  跳转链接
     * @param int    $time 停留时间 默认2秒
     * @param int    $icon 提示图标
     * @return string
     */
    function msg_success($msg = '', $url = '', $time = 3, $icon = 1) {
        return alert($msg, $url, $time, $icon);
    }
}

if (!function_exists('msg_error')) {

    /**
     * 失败时弹出层提示信息
     * @param string $msg  提示信息
     * @param string $url  跳转链接
     * @param int    $time 停留时间 默认2秒
     * @param int    $icon 提示图标
     * @return string
     */
    function msg_error($msg = '', $url = '', $time = 3, $icon = 2) {
        return alert($msg, $url, $time, $icon);
    }
}

if (!function_exists('clear_menu')) {

    /**
     * 清空菜单缓存
     */
    function clear_menu() {
        Cache::clear('menu');
    }
}


if (!function_exists('clear_basic')) {

    /**
     * 清空菜单缓存
     */
    function clear_basic() {
        Cache::clear('basic');
    }
}

if (!function_exists('get_ip')) {

    /**
     * 获取用户ip地址
     * @return array|false|string
     */
    function get_ip() {
        $ip = false;
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = false;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }
}

if (!function_exists('get_location')) {

    /**
     * 根据ip获取地理位置
     * @param string $ip
     * @return mixed
     */
    function get_location($ip = '') {
        empty($ip) && $ip = get_ip();
        //接口有问题
//        ini_set('user_agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3559.6 Safari/537.36');
//        $url = "http://ip.taobao.com/service/getIpInfo.php?ip={$ip}";
//        $ret = file_get_contents($url);
//        $arr = json_decode($ret, true);
//        $data =$arr['data'];
        $data = [
            'ip'      => $ip,
            'country' => '',
            'region'  => '',
            'city'    => '',
            'isp'     => '',
        ];
        return $data;
    }
}

if (!function_exists('install_substring')) {

    /**
     * 格式化安装配置信息
     * @param     $str
     * @param     $lenth
     * @param int $start
     * @return string
     */
    function install_substring($str, $lenth, $start = 0) {
        $len = strlen($str);
        $r = [];
        $n = 0;
        $m = 0;

        for ($i = 0; $i < $len; $i++) {
            $x = substr($str, $i, 1);
            $a = base_convert(ord($x), 10, 2);
            $a = substr('00000000 ' . $a, -8);

            if ($n < $start) {
                if (substr($a, 0, 1) == 0) {
                } elseif (substr($a, 0, 3) == 110) {
                    $i += 1;
                } elseif (substr($a, 0, 4) == 1110) {
                    $i += 2;
                }
                $n++;
            } else {
                if (substr($a, 0, 1) == 0) {
                    $r[] = substr($str, $i, 1);
                } elseif (substr($a, 0, 3) == 110) {
                    $r[] = substr($str, $i, 2);
                    $i += 1;
                } elseif (substr($a, 0, 4) == 1110) {
                    $r[] = substr($str, $i, 3);
                    $i += 2;
                } else {
                    $r[] = ' ';
                }
                if (++$m >= $lenth) {
                    break;
                }
            }
        }
        return join('', $r);
    }
}

if (!function_exists('parse_sql')) {

    /**
     * 格式化导入的sql语句
     * @param string $sql
     * @param int    $limit
     * @return array|string
     */
    function parse_sql($sql = '', $limit = 0) {
        if ($sql != '') {
            // 纯sql内容
            $pure_sql = [];

            // 多行注释标记
            $comment = false;

            // 按行分割，兼容多个平台
            $sql = str_replace(["\r\n", "\r"], "\n", $sql);
            $sql = explode("\n", trim($sql));

            // 循环处理每一行
            foreach ($sql as $key => $line) {
                // 跳过空行
                if ($line == '') {
                    continue;
                }

                // 跳过以#或者--开头的单行注释
                if (preg_match("/^(#|--)/", $line)) {
                    continue;
                }

                // 跳过以/**/包裹起来的单行注释
                if (preg_match("/^\/\*(.*?)\*\//", $line)) {
                    continue;
                }

                // 多行注释开始
                if (substr($line, 0, 2) == '/*') {
                    $comment = true;
                    continue;
                }

                // 多行注释结束
                if (substr($line, -2) == '*/') {
                    $comment = false;
                    continue;
                }

                // 多行注释没有结束，继续跳过
                if ($comment) {
                    continue;
                }

                // sql语句
                array_push($pure_sql, $line);
            }

            // 只返回一条语句
            if ($limit == 1) {
                return implode($pure_sql, "");
            }

            // 以数组形式返回sql语句
            $pure_sql = implode($pure_sql, "\n");
            $pure_sql = explode(";\n", $pure_sql);
            return $pure_sql;
        } else {
            return $limit == 1 ? '' : [];
        }
    }
}

if (!function_exists('curl')) {

    /**
     * 模拟请求
     * @return \app\common\service\CurlService
     */
    function curl() {
        return new \tool\Curl();
    }
}

if (!function_exists('__success')) {

    /**
     * 成功时返回的信息
     * @param $msg 消息
     * @return \think\response\Json
     */
    function __success($msg, $data = '',$code=0) {
        return json(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }
}

if (!function_exists('__error')) {

    /**
     * 错误时返回的信息
     * @param $msg 消息
     * @return \think\response\Json
     */
    function __error($msg, $data = '',$code=1) {
        return json(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }
}

if (!function_exists('is_mobile')) {

    /**
     * 判断客户端是否为手机
     * @return bool
     */
    function is_mobile() {
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        $is_pc = (strpos($agent, 'windows nt')) ? true : false;
        $is_mac = (strpos($agent, 'mac os')) ? true : false;
        $is_iphone = (strpos($agent, 'iphone')) ? true : false;
        $is_android = (strpos($agent, 'android')) ? true : false;
        $is_ipad = (strpos($agent, 'ipad')) ? true : false;
        if ($is_pc) return false;
        if ($is_mac) return true;
        if ($is_iphone) return true;
        if ($is_android) return true;
        if ($is_ipad) return true;
    }
}

if (!function_exists('get_time')) {

    /**
     * 获取当前时间
     * @return false|string
     */
    function get_time() {
        return date('Y-m-d H:i:s');
    }
}

if (!function_exists('code')) {

    /**
     * 生成随机数验证码
     * @param string $num
     * @return int
     */
    function code($num = '6') {
        $max = pow(10, $num) - 1;
        $min = pow(10, $num - 1);
        return rand($min, $max);
    }
}

if (!function_exists('get_config')) {

    /**
     * 获取配置信息
     * @param $group
     * @param $name
     */
    function get_config($group, $name) {
        $value = Db::name('SystemConfig')->where([
            'group' => $group,
            'name'  => $name,
        ])->value('value');
        return $value;
    }
}
if (!function_exists('P')) {

    /**
     * 打印日志
     * @param $data
     */
    function P($data) {
        \think\facade\Log::record($data, 'record');
    }
}

if(!function_exists('HomeDomain')){
    function HomeDomain(){
//        return 'http://www.huatuoyf.com';
    }
}

if(!function_exists('CDNDomain')){
    function CDNDomain(){
        return 'http://images.huatuoyf.com';
    }
}

// 公共助手函数

if (!function_exists('__'))
{

    /**
     * 获取语言变量值
     * @param string    $name 语言变量名
     * @param array     $vars 动态变量值
     * @param string    $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name))
            return $name;
        if (!is_array($vars))
        {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return Lang($name, $vars, $lang);
    }

}
/**
 * 数据及OBJECT 字符串过滤
 * @param $arr
 * @return mixed
 */
function hsc($arr) {
    foreach($arr as $k=>$v){
        if(is_array($v)){
            $arr[$k] = hsc($v);
        }else if(is_object($v)){
            $arr[$k] = hsc((array)$v);
        }else{
            $arr[$k] = htmlspecialchars(trim($v));
        }
    }
    return $arr;
}

if (!function_exists('buildToken'))
{

    /**
     * 生成Token
     * @param string    $param 用户参数值
     * @return mixed
     */
    function buildToken($param)
    {
        $str = md5(uniqid(md5('YiXiu_Hotel_session'), true).md5($param)); //生成一个Token
        $str = sha1($str); //加密
        return $str;
    }

}

if (!function_exists('checkToken'))
{
    /**
     * 验证Token
     * @param string    $token 用户Token
     * @param integer   $uid   用户ID
     * @param integer   $hid   酒店ID
     * @return mixed
     */
    function checkToken($token)
    {
        $localToken = cache('employee_'.$token);
        if(empty($localToken)){
            return ['code'=>2,'msg'=>'抱歉,请登录以获取访问权限 ￣□￣｜｜','data'=>[]];
        }
//        if($localToken == $token){
//            $newData = [
//                'id'    => $uid,
//                'token' => buildToken($uid),
//            ];
//            session('employee',$newData);
//            return ['code'=>0,'msg'=>'成功','data'=>[]];
//        }
//        return ['code'=>1,'msg'=>'错误! (〒︿〒)','data'=>[]];
        if($localToken != $token){
            return ['code'=>1,'msg'=>'错误! (〒︿〒)','data'=>[]];
        }
        $user_info = cache($token);
        // $hotel_ids = explode(',',$user_info['hotel_ids']);
        // if($user_info['id'] == $uid && in_array($hid,$hotel_ids)){
            return ['code'=>0,'msg'=>'成功','data'=>$user_info];
        // }
        // return ['code'=>1,'msg'=>'错误!','data'=>[]];
    }
}
function updateUserInfoByToken($token,$userinfo){
    
    cache($token,$userinfo);
}
function retGoValue(){
    return ['1'=>'水费','2'=>'电费','3'=>'煤气费'];
}

// 自定义规则计算方法

/**
 * 按抄表用量二级阶梯计费
 * @param $count int 抄表用量
 * @return $price int 金额
 */
function copyTableTwoCompute($count, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3')->find();

    // 计算
    if($count < $varArr['var1']) {
        $price = $varArr['var1'] * $varArr['var2'];
        return $price;
    } else {
        $price = $count * $varArr['var3'];
        return $price;
    }
}

/**
 * 按抄表用量三级阶梯计费
 * @param $count int 抄表用量
 * @return $price int 金额
 */
function copyTableThreeCompute($count, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3, var4, var5')->find();

    // 计算
    if($count < $varArr['var1']) {
        $price = $count * $varArr['var2'];
        return $price;
    } else if($count > $varArr['var1'] && $count < $varArr['var3']) {
        $price = $varArr['var1'] * $varArr['2'] + ($count - $varArr['var1']) * $varArr['var4'];
        return $price;
    } else {
        $price = $varArr['var1'] * $varArr['var2'] + ($count - $varArr['var1']) * $varArr['var4'] + ($count - $varArr['var3']) * $varArr['var5'];
        return $price;
    }
}

/**
 * 按车辆排量三级阶梯计费
 * @param $power int 排量
 * @return $price int 金额
 */
function carHorsepowerThreeCompute($power, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3, var4, var5')->find();

    // 计算
    if($power < $varArr['var1']) {
        return $varArr['var2'];
    } else if($power > $varArr['var1'] && $power <= $varArr['var3']) {
        return $varArr['var4'];
    } else {
        return $varArr['var5'];
    }
}

/**
 * 按楼宇层数二级阶梯计费（不封顶）
 * @param $floor int 层数
 * @return $price int 金额
 */
function buildFloorTwoNottopCompute($floor, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3, var4')->find();

    // 计算
    if($floor < $varArr['var1']) {
        return $varArr['var2'];
    } else {
        $price = $varArr['var3'] + ($floor - $varArr['var1']) * $varArr['var4'];
        return $price;
    }
}

/**
 * 按楼宇层数二级阶梯计费（封顶）
 * @param $floor int 层数
 * @return $price int 金额
 */
function buildFloorTwoCompute($floor, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3, var4, var5')->find();

    // 计算
    $price = 0;
    if($floor < $varArr['var1']) {
        $price = $varArr['var2'];
    } else {
        $price = $varArr['var2'] + ($floor - $varArr['var1']) * $varArr['var3'];
    }

    if($price > $varArr['var4']) {
        return $varArr['var5'];
    }
}


/**
 * 按楼宇层数建筑面积四级阶梯计费
 * @param $floor int 层数
 * @param $area float 建筑面积
 * @return $price int 金额
 */
function buildFloorAreaFourCompute($floor, $area, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3, var4, var5, var6, var7')->find();

    // 计算
    if($floor > 0 && $floor <= $varArr['var1']) {
        return $varArr['var2'] * $area;
    } else if ($floor > $varArr['var1'] && $floor <= $varArr['var3']) {
        return $varArr['var4'] * $area;
    } else if($floor > $varArr['var3'] && $floor <= $varArr['var5']) {
        return $varArr['var6'] * $area;
    } else {
        return $varArr['var7'] * $area;
    }
}

/**
 * 按楼宇层数抄表用量五级阶梯计费
 * @param $floor int 层数
 * @param $count int 抄表用量
 * @return $price int 金额
 */
function buildFloorTableFiveCompute($floor, $count, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3, var4, var5, var6, var7, var8, var9')->find();

    // 计算
    if($floor <= $varArr['var1']) {
        return $varArr['var2'] * $count;
    } else if ($floor > $varArr['var1'] && $floor <= $varArr['var3']) {
        return $varArr['var4'] * $count;
    } else if ($floor > $varArr['var3'] && $floor <= $varArr['var5']) {
        return $varArr['var6'] * $count;
    } else if ($floor > $varArr['var5'] && $floor <= $varArr['var7']) {
        return $varArr['var8'] * $count;
    } else if($floor > $varArr['var7']) {
        return $varArr['var9'] * $count;
    }
}

/**
 * 按楼宇层数建筑面积五级阶梯计费
 * @param $floor int 层数
 * @param $area float 面积
 * @return $price int 金额
 */
function buildFloorAreaFiveCompute($floor, $area, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3, var4, var5, var6, var7, var8, var9')->find();
    // 计算
    if($floor >= 0 && $floor <= $varArr['var1']) {
        return $varArr['var2'] * $area;
    } else if ($floor > $varArr['var1'] && $floor <= $varArr['var3']) {
        return $varArr['var4'] * $area;
    } else if($floor > $varArr['var3'] && $floor <= $varArr['var5']) {
        return $varArr['var6'] * $area;
    } else if ($floor > $varArr['var5'] && $floor <= $varArr['var7']) {
        return $varArr['var8'] * $area;
    } else {
        return $varArr['var9'] * $area;
    }
}

/**
 * 按楼宇层数无规律固定金额七级阶梯计费
 * @param $floor int 层数
 * @return $price int 金额
 */
function buildFloorNotLawSevenCompute($floor, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3, var4, var5, var6, var7, var8, var9, var10 ,var11, var12, var13')->find();

    // 计算
    if($floor <= $varArr['var1']) {
        return $varArr['var2'];
    } else if($floor > $varArr['var1'] && $floor <= $varArr['var3']) {
        return $varArr['var4'];
    } else if($floor > $varArr['var3'] && $floor <= $varArr['var5']) {
        return $varArr['var6'];
    } else if($floor > $varArr['var5'] && $floor <= $varArr['var7']) {
        return $varArr['var8'];
    } else if($floor > $varArr['var7'] && $floor <= $varArr['var9']) {
        return $varArr['var10'];
    } else if($floor > $varArr['var9'] && $floor <= $varArr['var11']) {
        return $varArr['var12'];
    } else if($floor > $varArr['var11']) {
        return $varArr['var13'];
    }
}



/**
 * 房屋建筑面积乘以单价加固定金额
 * @param $area float 面积
 * @return $price int 金额
 */
function areaAndOnlyPriceCompute($area, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2')->find();
    // 计算
    return $varArr['var1'] * (int)$area + $varArr['var2'];
}



/**
 * 按楼宇层数二级阶梯计费（封顶）6个参数
 * @param $floor int 层数
 * @return $price int 金额
 */
function buildFloorCompute($floor, $id) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2, var3, var4, var5, var6')->find();

    // 计算
    $price = 0;
    if($floor < $varArr['var1']) {
        $price = $varArr['var2'];
    } else {
        $price = $varArr['var3'] ($floor - $varArr['var1']) * $varArr['var4'];
    }

    if($price > $varArr['var5']) {
        return $varArr['var6'];
    }
}
/**
 * 按面积计算公摊
 * @param $area float 单户面积
 * @param $areaAll float 总面积
 * @param $num float 户数
 * @param $numAll float 总户数
 * @param $ratio float 公摊费
 * @param  $kes float 房屋系数
 * @return $price int 金额
 */
function buildAreaGT($id,$area,$areaAll,$num,$numAll,$ratio,$kes) {
    // 取数值
    $varArr = Db::name('wy_toll_formula_user')->where('id', $id)->field('var1, var2')->find();
    // dump($area);
    // dump($areaAll);
    // dump($num);
    // dump($numAll);
    // dump($ratio);
    // dump($kes);
    // dump((float)$varArr['var1']);
    // dump((float)$varArr['var2']);
    // die;
    return $ratio/$areaAll*($area*$kes)*((int)$varArr['var1']/100)+$ratio/$numAll*$num*((int)$varArr['var2']/100);
}
function cityList($arr,$key){
    $name='';
    foreach($arr as $k=>$v){
        if($v['value']==$key){
            $name = $v['label'];
            return $name;
        }elseif (@$v['children']) {
            $name=cityList($v['children'],$key);
            if($name){
                return $name;
            }
        }
    }
    return $name;
}
function getAreaStr($strArea){
    $arr= explode(',',$strArea);
    $areastr='';
    foreach($arr as $k=>$v){
        if($k==count($arr)-1){
            $areastr.=cityList(config('citys.citys'),$v);
        }else {
            $areastr.=cityList(config('citys.citys'),$v).'/';
        }
        
    }
    return $areastr;
}

// 获取房屋类型
function getHousesType($type) {
    $typeList = [0=>'其它',1=>'住宅',2=>'公寓',3=>'办公',4=>'厂房',5=>'仓库',6=>'商铺',7=>'酒店',8=>'别墅',9=>'其它'];
    return $typeList[$type];
}
function getIdformhouseType($name){
    $typeList = [0=>'其它',1=>'住宅',2=>'公寓',3=>'办公',4=>'厂房',5=>'仓库',6=>'商铺',7=>'酒店',8=>'别墅',9=>'其它'];
    foreach($typeList as $k=>$v){
        if($v==$name){
            return $k;
        }
    }
    return 1;
}
function getArgs($fun) {
    $argNum = [];
    switch($fun) {
        case 'copyTableTwoCompute':
            return $argNum = ['抄表用量'];
            break;
        case 'copyTableThreeCompute':
            return $argNum = ['抄表用量'];
            break;
        case 'carHorsepowerThreeCompute':
            return $argNum = ['车辆排量'];
            break;
        case 'buildFloorTwoNottopCompute':
            return $argNum = ['楼宇层数'];
            break;
        case 'buildFloorTwoCompute':
            return $argNum = ['楼宇层数'];
            break;
        case 'buildFloorAreaFourCompute':
            return $argNum = ['楼宇层数','建筑面积'];
            break;
        case 'buildFloorTableFiveCompute':
            return $argNum = ['楼宇层数','抄表用量'];
            break;
        case 'buildFloorAreaFiveCompute':
            return $argNum = ['楼宇层数','建筑面积'];
            break;
        case 'buildFloorNotLawSevenCompute':
            return $argNum = ['楼宇层数'];
            break;
        case 'areaAndOnlyPriceCompute':
            return $argNum = ['建筑面积'];
            break;
        case 'buildFloorCompute':
            return $argNum = ['楼宇层数'];
            break;
        case 'buildAreaGT':
            return $argNum = ['单户面积','总面积','户数','总户数','公摊费','面积系数'];
            break;
    }
}
function getGSgo($fun,$id,$floor=0,$area=0,$power=0,$count=0,$areaAll=0,$num=0,$numAll=0,$ratio=0,$kes=0)
{
    switch($fun) {
        case 'copyTableTwoCompute':
            return call_user_func($fun,$count,$id);
            break;
        case 'copyTableThreeCompute':
            return call_user_func($fun,$count,$id);
            break;
        case 'carHorsepowerThreeCompute':
            return call_user_func($fun,$power,$id);
            break;
        case 'buildFloorTwoNottopCompute':
            return call_user_func($fun,$floor,$id);
            break;
        case 'buildFloorTwoCompute':
            return call_user_func($fun,$floor,$id);
            break;
        case 'buildFloorAreaFourCompute':
            return call_user_func($fun,$floor,$area,$id);
            break;
        case 'buildFloorTableFiveCompute':
            return call_user_func($fun,$floor,$count,$id);
            break;
        case 'buildFloorAreaFiveCompute':
            return call_user_func($fun,$floor,$area,$id);
            break;
        case 'buildFloorNotLawSevenCompute':
            return call_user_func($fun,$floor,$id);
            return $argNum = ['楼宇层数'];
            break;
        case 'areaAndOnlyPriceCompute':
            return call_user_func($fun,$area,$id);
            break;
        case 'buildFloorCompute':
            return call_user_func($fun,$floor,$id);
            break;
        case 'buildAreaGT':
            return call_user_func($fun,$id,$area,$areaAll,$num,$numAll,$ratio,$kes);
            break;
    }
}
function getMonthNum( $date1, $date2){
    $date1 = strtotime($date1);
    $date2 = strtotime($date2);
    
    return round(($date2-$date1)/3600/24/30);
}
function round_num($num,$slen=2){

	if($len = strpos($num,'.')){

		$dian_num = substr($num,$len+1,$len+$slen+1);//获取小数点后面的数字

		if(strlen($dian_num) >= $slen){//判断小数点后面的数字长度是否大于2

			$new_num = substr($num,0,$len+$slen+1);

		}else{//补0

			$new_num = $num.'0';

		}

	}else{

		$new_num = $num.'00';

	}

	return $new_num;

}
function formatPrice($price,$type,$num){
    if($type==1){
        return round_num($price,$num);
    }else {
        return round($price,$num);
    }
}

/**
 * PHP 导入EXCLE
 * @param $filename
 * @return int
 * @throws PHPExcel_Exception
 * @throws PHPExcel_Reader_Exception
 */
function inExcel($filename,$bd_info_id,$modelname,$site=1,$xl='lsx',$user_id = 0,$page=1)
{
    if ($xl == 'ls') {
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
    } else {
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
    }
    /**  Advise the Reader that we only want to load cell data  **/
    $objReader->setReadDataOnly(true);
    /**  Load $inputFileName to a PHPExcel Object  **/
    $objPHPExcel = $objReader->load($filename);
    $sheet = $objPHPExcel->getSheet(0);
    $highestRow = $sheet->getHighestRow(); // 取得总行数
    //循环读取excel文件,读取一条,插入一条
    $model = model($modelname);
    $lit=[];
    switch($modelname){
        case 'wy_houses':
            for ($j = 2; $j <= $highestRow; $j++) {
                $building_txt=$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                $unit=$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $building_id=model('wy_building')->where('name','like','%'.$building_txt.'%')->where('bd_info_id',$bd_info_id)->value('id');
                $unit_id=model('wy_unit')->where('name','like','%'.$unit.'%')->where('building_id',$building_id)->where('bd_info_id',$bd_info_id)->value('id');
                $h_name = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                if (!$building_txt || !$unit || !$h_name) {
                    continue;
                }
                if($unit_id && $building_id){
                    $temp['bd_info_id']=$bd_info_id;
                    $temp['building_id'] = $building_id;
                    $temp['unit_id'] = $unit_id;
                    $temp['name'] = $h_name;
                    $temp['floor'] = (int)$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                    $temp['area'] = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                    $temp['num'] = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()?$objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue():0;
                    $temp['ratio'] = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                    $temp['houses_type'] = getIdformhouseType($objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue());
                    $temp['direction'] = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue();
                    $temp['over_house'] = $objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue();
                    $temp['is_gt'] = $objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue();
                    $temp['time'] = $objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue();
                    $temp['years'] = $objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue()?$objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue():0;
                    $temp['room_numbers'] = $objPHPExcel->getActiveSheet()->getCell("N" . $j)->getValue();
                    $temp['hall_numbers'] = $objPHPExcel->getActiveSheet()->getCell("O" . $j)->getValue();
                    $temp['guard_numbers'] = $objPHPExcel->getActiveSheet()->getCell("P" . $j)->getValue();
                    $temp['remarks'] = $objPHPExcel->getActiveSheet()->getCell("Q" . $j)->getValue();
                    $temp['weights'] = $objPHPExcel->getActiveSheet()->getCell("R" . $j)->getValue()?$objPHPExcel->getActiveSheet()->getCell("R" . $j)->getValue():0;    
                    // 判断是否重复
                    $is_hased=$model
                    ->where([['bd_info_id','=',$temp['bd_info_id']],['building_id','=',$temp['building_id']],['unit_id','=',$temp['unit_id']],['name','=',$temp['name']]])
                    ->where('is_deleted','=','0')->find();
                    if(!$is_hased){
                        $lit[]=$temp;
                    }
                }
            }
            $ret=$model->saveAll($lit,true);
            if($ret){
                return ['code' => 0, 'msg' => '导入成功', 'data' => []];
                
            }else {
                return ['code' => 1, 'msg' => '导入错误', 'data' => []];
            }
            break;
        case 'wy_car_area':
            for ($j = 2; $j <= $highestRow; $j++) {
               
                $temp['bd_info_id']=$bd_info_id;
                $temp['name'] = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                $temp['area'] = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $temp['status'] = (int)$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue()? (int)$objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue():1;
                $temp['remarks'] = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                $temp['type'] = (int)$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue()?(int)$objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue():1;
                $n = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();
                $g = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                $add_uid = type_hao_user($bd_info_id,'车位',$temp['name'],$n,$g);
                if (!$add_uid) {
                    continue;
                }
                $temp['house_user_id'] = $add_uid;
                $lit[$j-2]=$temp;
            }

            $ret=$model->saveAll($lit);
            if($ret){
                return ['code' => 0, 'msg' => '导入成功', 'data' => []];
                
            }else {
                return ['code' => 1, 'msg' => '导入错误', 'data' => []];
            }
            break;
        case 'wy_car':
            for ($j = 2; $j <= $highestRow; $j++) {
                $carAreaName=$objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                $carArea=model('wy_car_area')->where('name','like',$carAreaName."%")->where('bd_info_id',$bd_info_id)->value('id');
                if($carArea){
                    $temp['bd_info_id']=$bd_info_id;
                    $temp['car_area_id'] = $carArea?$carArea:0;
                    $temp['stop_numbers'] = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                    $temp['username'] = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                    $temp['phone'] = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                    $temp['name'] = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                    $temp['horsepower'] = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();
                    $temp['car_model'] = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                    $temp['color'] = $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue();
                    $temp['qq'] = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue();
                    $temp['wechat'] = $objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue();
                    $temp['email'] = $objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue();
                    $temp['family_tel'] = $objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue();
                    $temp['remarks'] = $objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue();
                    $lit[$j-2]=$temp;
                }
                
                
            }

            $ret=$model->saveAll($lit);
            if($ret){
                return ['code' => 0, 'msg' => '导入成功', 'data' => []];
                
            }else {
                return ['code' => 1, 'msg' => '导入错误', 'data' => []];
            }
            break;
        case 'wy_copy_table':
            $bd_id = $bd_info_id;
            for ($j = 3; $j <= $highestRow; $j++) {
                $temp = [];
                $loudong = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                $danyuan = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $build_id = Db::name('wy_building')->where(['name'=>$loudong,'bd_info_id'=>$bd_id])->value('id');
                $unit_id = Db::name('wy_unit')->where(['name'=>$danyuan,'bd_info_id'=>$bd_id,'building_id'=>$build_id])->value('id');
                $hou = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                $pro = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                $det = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                $start_time = gmdate('Y-m-d H:i:s',\PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()));
                $end_time = gmdate('Y-m-d H:i:s',\PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue()));
                $temp['ratio'] = $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue();
                $temp['start_k'] = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue() ?: '';
                $temp['end_k'] = $objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue() ?: '';
                $temp['times'] = $objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue() ?: '';
                $lei = $objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue();
                $temp['remarks'] = $objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue();
                if (in_array(trim($lei),['水电费','水电'])) {
                    $temp['type'] = 1;
                } else {
                    $temp['type'] = 2;
                }
                $temp['bd_info_id'] = $bd_id;
                $temp['start_time'] = excel_date_format($start_time);
                $temp['end_time'] = excel_date_format($end_time);
                $temp['project_id'] = model('toll_project')->where('name',$pro)->value('id');
                $temp['project_detial_id'] = model('toll_project_detial')->where('name',$det)->value('id');
                $house = model('wy_houses')->where(['name'=>$hou,'bd_info_id'=>$bd_id,'building_id'=>$build_id,'unit_id'=>$unit_id])->field('id,bd_info_id,building_id,unit_id')->find();
                if (!$house) {
                    continue;
                }
                $temp['building_id'] = $build_id;
                $temp['unit_id'] = $unit_id;
                $temp['house_id'] = $house['id'];
                $user_id = model('wy_house_user')->where('houses_id',$house['id'])->value('id');
                $temp['user_id'] = $user_id;
                $has = model('wy_copy_table')->where(['house_id'=>$house['id'],'project_id'=>$temp['project_id'],'project_detial_id'=>$temp['project_detial_id'],'bd_info_id'=>$bd_id,'start_time'=>$start_time,'end_time'=>$end_time])->value('id');
                if ($site == 1 && !$has) {
                    $lit[$j-3]=$temp;
                } elseif ($site == 2 && $has) {
                    $temp['id'] = $has;
                    $lit[$j-3]=$temp;
                }
            }
            $ret = $model->saveAll($lit);
            if($ret){
                return ['code' => 0, 'msg' => '导入成功', 'data' => []];
            }else {
                return ['code' => 1, 'msg' => '导入错误', 'data' => []];
            }
            break;
        case 'wy_payment':
            $new_id = 0;
            $p_id = 0;
            $style_text = [
                '线下支付-现金' => '1',
                '线下支付-支票' => '2',
                '线下支付-银行转账' => '3',
                '线下支付-pos机刷卡' => '4',
                '线下支付-支付宝直接转账' => '5',
                '线下支付-微信直接转账' => '6',
                '小区收款码-支付宝' => '7',
                '小区收款码-微信' => '8'
            ];
            $status_text = [
                '未缴' => '0',
                '已缴' => '1',
                '已退' => '2',
                '撤销' => '3'
            ];
            $type_text = [
                '房屋' => '1',
                '车辆' => '2',
                '车位' => '3',
                '住户' => '4',
                '车牌' => '2'
            ];
            for ($j = 3; $j <= $highestRow; $j++) {
//                $ifo = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $hao = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                $type = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $name = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                $phone = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                $pay_name = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                $temp['price'] = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();
                $temp['money'] = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                $temp['pay_style'] = $style_text[$objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue()];
                $temp['status'] = $status_text[$objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue()];
                $temp['pay_time'] = gmdate('Y-m-d H:i:s',\PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue()));
                $start_time = gmdate('Y-m-d H:i:s',\PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue()));
                $end_time = gmdate('Y-m-d H:i:s',\PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue()));
                $temp['start_time'] = $start_time;
                $temp['end_time'] = $end_time;
                $temp['remarks'] = $objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue();
                $months = ceil((strtotime($end_time) - strtotime($start_time)) / (86400 * 30));
                $bd_id = $bd_info_id;
                $user = model('wy_house_user')->where('phone',$phone)->field('id,name,houses_id,phone')->find();
                $add_uid = type_hao_user($bd_id,$type,$hao,$phone,$name);
                if (!$add_uid) {
                    continue;
                }
                if (strstr($type,'车位')) {
                    $tx = model('wy_car_area')->where(['name'=>$hao,'bd_info_id'=>$bd_id])->value('id');
                    $temp['car_area_id'] = $tx;
                    $trr['car_area_id'] = $tx;
                    $trr['car_area_name'] = $hao;
                    $prr['car_area_id'] = $tx;
                    $has = Db::name('wy_payment')->where(['bd_info_id'=>$bd_id,'car_area_id'=>$tx,'house_user_id'=>$add_uid,'pay_time'=>$temp['pay_time'],'start_time'=>$start_time,'end_time'=>$end_time])->value('id');
                } elseif (strstr($type,'车牌') || strstr($type,'车辆')) {
                    $tx = model('wy_car')->where(['name'=>$hao,'bd_info_id'=>$bd_id])->value('id');
                    $temp['car_id'] = $tx;
                    $trr['car_id'] = $tx;
                    $trr['car_name'] = $hao;
                    $prr['car_id'] = $tx;
                    $has = Db::name('wy_payment')->where(['bd_info_id'=>$bd_id,'car_id'=>$tx,'house_user_id'=>$add_uid,'pay_time'=>$temp['pay_time'],'start_time'=>$start_time,'end_time'=>$end_time])->value('id');
                } else{
                    $tx = model('wy_houses')->where(['name'=>$hao,'bd_info_id'=>$bd_id])->value('id');
                    $temp['houses_id'] = $tx;
                    $trr['houses_id'] = $tx;
                    $trr['houses_name'] = $hao;
                    $prr['house_id'] = $tx;
                    $has = Db::name('wy_payment')->where(['bd_info_id'=>$bd_id,'houses_id'=>$tx,'house_user_id'=>$add_uid,'pay_time'=>$temp['pay_time'],'start_time'=>$start_time,'end_time'=>$end_time])->value('id');
                }
                if (!$bd_id || !$tx) {
                    continue;
                }
                $temp['name'] = $pay_name;
                $temp['bd_info_id'] = $bd_id;
                $temp['house_user_id'] = $add_uid;
                $temp['action_user'] = $user_id;
                if ($site == 1 && !$has) {
                    $new_id = Db::name('wy_payment')->insertGetId($temp);
                    $p_id = $new_id;
//                    Db::name('wy_house_user')->where('id',$add_uid)->setInc('money',$temp['price']);
                } elseif ($site == 2 && $has) {
                    $temp['id'] = $has;
                    $new_id = Db::name('wy_payment')->save($temp);
                    $p_id = $has;
//                    Db::name('wy_house_user')->where('id',$add_uid)->setInc('money',$temp['price']);
                }
                for ($i = 0 ; $i < $months ; $i++) {
                    $trr['payment_id'] = $p_id;
                    $trr['status'] = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue();
                    $trr['type'] = strstr($pay_name,'物业费') ? '房屋' : '临时停车';
                    $trr['user_id'] = $user['id'];
                    $trr['user_name'] = $user['name'];
                    $trr['user_phone'] = $user['phone'];
                    $trr['start_time'] = date('Y-m-d H:i:s',strtotime($start_time) + (86400 * 30 * $i));
                    $trr['pay_style'] = $temp['pay_style'];
                    $trr['end_time'] = $i + 1 == $months ? $end_time : date('Y-m-d H:i:s',strtotime($start_time) + (86400 * 30 * ($i + 1)));
                    $trr['name'] = $name;
                    $trr['price'] = $temp['price'];
                    $trr['money'] = $temp['money'];
                    $trr['action_user'] = $user_id;
                    Db::name('wy_payment_store')->insert($trr);
                    $prr['bd_info_id'] = $bd_id;
                    $prr['type'] = @$type_text[$type] ?: '';
                    $prr['name'] = $name;
                    $prr['price'] = $temp['price'];
                    $prr['one_money'] = $temp['price'];
                    $prr['num'] = 1;
                    $prr['money'] = $temp['money'];
                    $prr['start_time'] = $trr['start_time'];
                    $prr['end_time'] = $trr['end_time'];
                    $prr['remarks'] = $temp['remarks'];
                    $prr['createtime'] = date('Y-m-d',time());
                    $prr['pay_status'] = 1;
                    Db::name('wy_no_payment')->insert($prr);
                }
                unset($temp);
                unset($trr);
                unset($prr);
            }
            $ret = $model->saveAll($lit);
            if($ret || $new_id){
                return ['code' => 0, 'msg' => '导入成功', 'data' => []];

            }else {
                return ['code' => 1, 'msg' => '导入失败', 'data' => []];
            }
            break;
        case 'wy_no_payment':
            $type_text = [
                '房屋' => '1',
                '车辆' => '2',
                '车位' => '3',
                '住户' => '4'
            ];
            $bd_id = $bd_info_id;
            for ($j = 3; $j <= $highestRow; $j++) {
                $loudong = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $danyuan = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                $build_id = Db::name('wy_building')->where(['name'=>$loudong,'bd_info_id'=>$bd_id])->value('id');
                $unit_id = Db::name('wy_unit')->where(['name'=>$danyuan,'bd_info_id'=>$bd_id,'building_id'=>$build_id])->value('id');
                $hao = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                $type = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                $start_time = gmdate('Y-m-d H:i:s',\PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue()));
                $end_time = gmdate('Y-m-d H:i:s',\PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue()));
                if (strstr($type,'车位')) {
                    $tx = model('wy_car_area')->where(['name'=>$hao,'bd_info_id'=>$bd_id])->value('id');
                    $temp['car_area_id'] = $tx;
                    $has = model('wy_no_payment')->where(['bd_info_id'=>$bd_id,'car_area_id'=>$tx,'start_time'=>$start_time,'end_time'=>$end_time])->value('id');
                } elseif (strstr($type,'车牌')) {
                    $tx = model('wy_car')->where(['name'=>$hao,'bd_info_id'=>$bd_id])->value('id');
                    $temp['car_id'] = $tx;
                    $has = model('wy_no_payment')->where(['bd_info_id'=>$bd_id,'car_id'=>$tx,'start_time'=>$start_time,'end_time'=>$end_time])->value('id');
                } else{
                    $tx = model('wy_houses')->where(['name'=>$hao,'bd_info_id'=>$bd_id,'building_id'=>$build_id,'unit_id'=>$unit_id])->value('id');
                    $temp['house_id'] = $tx;
                    $temp['building_id'] = $build_id;
                    $has = model('wy_no_payment')->where(['bd_info_id'=>$bd_id,'house_id'=>$tx,'start_time'=>$start_time,'end_time'=>$end_time])->value('id');
                }
                if (!$bd_id || !$tx) {
                    continue;
                }
                $temp['bd_info_id'] = $bd_id;
                $temp['type'] = $type_text[$type];
                $temp['name'] = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()?:'';
                $temp['price'] = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();;
                $temp['money'] = $objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue();;
                $temp['start_time'] = $start_time;
                $temp['end_time'] = $end_time;
                $temp['one_money'] = $objPHPExcel->getActiveSheet()->getCell("N" . $j)->getValue();
                $temp['num'] = $objPHPExcel->getActiveSheet()->getCell("O" . $j)->getValue();
                $temp['offer'] = $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue();
                $temp['overdue'] = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue();
                $temp['deduction'] = $objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue();
                $temp['remarks'] = $objPHPExcel->getActiveSheet()->getCell("P" . $j)->getValue();
                $temp['createtime'] = date('Y-m-d',time());
                if ($site == 1 && !$has) {
                    $lit[$j-3]=$temp;
                } elseif ($site == 2 && $has) {
                    $temp['id'] = $has;
                    $lit[$j-3]=$temp;
                } elseif ($site == 2 && !$has) {
                    $lit[$j-3]=$temp;
                }
                unset($temp);
            }
            $ret = $model->saveAll($lit);
            if($ret){
                return ['code' => 0, 'msg' => '导入成功', 'data' => []];

            }else {
                return ['code' => 1, 'msg' => '导入错误', 'data' => []];
            }
            break;
        case 'deposit_list':
            $status = 0;
            $bd_id = $bd_info_id;
            for ($j = 2; $j <= $highestRow; $j++) {
                $loudong = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                $danyuan = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                $build_id = Db::name('wy_building')->where(['name'=>$loudong,'bd_info_id'=>$bd_id])->value('id');
                $unit_id = Db::name('wy_unit')->where(['name'=>$danyuan,'bd_info_id'=>$bd_id,'building_id'=>$build_id])->value('id');
                $hao = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                $user_name = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                $phone = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();
                $price = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();
                $money = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                $category = $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue();
                $remark = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue();
                $house = model('wy_houses')->where(['name'=>$hao,'bd_info_id'=>$bd_id,'building_id'=>$build_id,'unit_id'=>$unit_id])->field('id,building_id,unit_id')->find();
                if (!$bd_id || !$house) {
                    continue;
                }
                $uid = Db::name('wy_house_user')->where('phone',$phone)->value('id') ?: 0;
                if (!$uid) {
                    $srr['phone'] = $phone;
                    $srr['gender'] = 3;
                    $srr['name'] = $user_name;
                    $srr['status'] = 2;
                    $uid = Db::name('wy_house_user')->insertGetId($srr);
                }
                if ($uid) {
                    $type = 1;
                    if(empty($category)) {
                        $balance = Db::name('wy_deposit_list')->where(['house_user_id' => $uid, 'type' => $type])->value('balance');
                    } else {
                        $type = 2;
                        $balance = Db::name('wy_deposit_list')->where(['house_user_id' => $uid, 'type' => $type, 'category' => $category])->value('balance');
                    }
                    $houses_id = $house['id'];
                    if($balance) {
                        $param['balance'] = $balance + floatval($price);
                        if ($type == 1) {
                            $status = Db::name('wy_deposit_list')->where(['house_user_id' => $uid, 'type' => $type])->update($param);
                            $bid = Db::name('wy_deposit_list')->where(['house_user_id' => $uid, 'type' => $type])->value('id');
                        } else {
                            $status = Db::name('wy_deposit_list')->where(['house_user_id' => $uid, 'type' => $type,'category' => $category])->update($param);
                            $bid = Db::name('wy_deposit_list')->where(['house_user_id' => $uid, 'type' => $type,'category' => $category])->value('id');
                        }
                    } else {
                        $param['bd_info_id'] = $bd_id;
                        $param['house_user_id'] = $uid;
                        $param['houses_id'] = $houses_id;
                        $param['balance'] = floatval($price);
                        $param['price'] = floatval($price);
                        $param['money'] = floatval($money);
                        $param['type'] = $type;
                        $param['category'] = $category;
                        $param['remarks'] = $remark;
                        $param['status'] = 1;
                        $status = Db::name('wy_deposit_list')->insertGetId($param);
                        $bid = $status;
                    }
                    $has_money = Db::name('wy_house_user')->where('id',$uid)->value('money');
                    if ($has_money > 0) {
                        Db::name('wy_house_user')->where('id',$uid)->setInc('money',floatval($price));
                    } else {
                        Db::name('wy_house_user')->where('id',$uid)->setField('money',floatval($price));
                    }
                    $store['deposit_list_id'] = $bid ?: 0;
                    $store['bd_info_id'] = $bd_id;
                    $store['house_user_id'] = $uid;
                    $store['price'] = floatval($price);
                    $store['money'] = floatval($money);
                    $store['type'] = 1;
                    $store['come'] = "excel导入";
                    $store['createtime'] = date('Y-m-d H:i:s', time());
                    $store['remarks'] = $remark;
                    $store['user_name'] = $user_name;
                    $store['user_phone'] = $phone;
                    Db::name('wy_deposit_list_store')->insert($store);
                }
            }
//            $ret = $model->saveAll($lit);
            if($status){
                return ['code' => 0, 'msg' => '导入成功', 'data' => []];

            }else {
                return ['code' => 1, 'msg' => '导入错误', 'data' => []];
            }
            break;
        case 'wy_house_user':
                $toalPage=ceil(($highestRow-1) / 100);
                if($toalPage<$page){
                    return ['code' => 0, 'msg' => '导入成功', 'data' => []];
                }
                $lit=[];
                for ($j = 2+($page-1)*100; $j < 2+($page-1)*100+100; $j++) {
                    $houses_name=$objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();
                    $houseInfo=model('wy_houses')->where('name',$houses_name)->where('bd_info_id',$bd_info_id)->find();
                    if($houseInfo){
                        $temp['bd_info_id']=$bd_info_id;
                        $temp['building_id'] = $houseInfo['building_id'];
                        $temp['unit_id'] = $houseInfo['unit_id'];
                        $temp['houses_id'] = $houseInfo['id'];
                        $temp['name'] = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();
                        $sex_text=$objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();
                        $gender_text='';
                        switch($sex_text){
                            case '男':
                                $gender_text=1;
                            break;
                            case '女':
                                $gender_text=2;
                            break;
                            default:
                                $gender_text=3;
                        }
                        $temp['gender'] = $gender_text;
                        $temp['phone'] = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();
                        $temp['type'] =getUsertypeId($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue());
                        $temp['createtime'] = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();
                        $temp['license'] = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();
                        $temp['sos_user'] = $objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue();
                        $temp['sos_call'] = $objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue();
                        $temp['card_numbers'] = $objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue();
                        $temp['work_area'] = $objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue();
                        $temp['in_time'] = excel_date_format($objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue());
                        $temp['in_text'] = $objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue();
                        $temp['qq'] = $objPHPExcel->getActiveSheet()->getCell("N" . $j)->getValue();
                        $temp['wechat'] = $objPHPExcel->getActiveSheet()->getCell("O" . $j)->getValue();
                        $temp['email'] = $objPHPExcel->getActiveSheet()->getCell("P" . $j)->getValue();
                        $temp['tel'] = $objPHPExcel->getActiveSheet()->getCell("Q" . $j)->getValue();
                        $temp['pet_breed'] = $objPHPExcel->getActiveSheet()->getCell("R" . $j)->getValue();  
                        $temp['pet_weight'] = $objPHPExcel->getActiveSheet()->getCell("S" . $j)->getValue()?$objPHPExcel->getActiveSheet()->getCell("S" . $j)->getValue():0;  
                        $temp['pet_category'] = $objPHPExcel->getActiveSheet()->getCell("T" . $j)->getValue()?$objPHPExcel->getActiveSheet()->getCell("T" . $j)->getValue():0;  
                        $temp['pet_card'] = $objPHPExcel->getActiveSheet()->getCell("U" . $j)->getValue()?$objPHPExcel->getActiveSheet()->getCell("U" . $j)->getValue():0;
                        $temp['po_status'] = $objPHPExcel->getActiveSheet()->getCell("V" . $j)->getValue();  
                        $temp['marriage'] = $objPHPExcel->getActiveSheet()->getCell("W" . $j)->getValue(); 
                        $temp['account_type'] = $objPHPExcel->getActiveSheet()->getCell("X" . $j)->getValue()?$objPHPExcel->getActiveSheet()->getCell("X" . $j)->getValue():1;  
                        $temp['address'] = $objPHPExcel->getActiveSheet()->getCell("Y" . $j)->getValue();  
                        $temp['tem_permit'] = $objPHPExcel->getActiveSheet()->getCell("Z" . $j)->getValue();  
                        $temp['tem_type'] = $objPHPExcel->getActiveSheet()->getCell("AA" . $j)->getValue();  
                        $temp['remarks'] = $objPHPExcel->getActiveSheet()->getCell("AB" . $j)->getValue();  
                        $temp['registry_text'] = 'excel';

                        $check = '/^(1(([35789][0-9])|(47)))\d{8}$/';
                        $check_tel='/^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/';
                        if (preg_match($check, $temp['phone']) || preg_match($check_tel, $temp['phone'])) {
           
                            // 判断是否重复
                            $is_hased=$model
                            ->where([['phone','=',$temp['phone']]])->find();
                            if(!$is_hased){
                                $arrid=$model->insertGetId($temp,true);
                                // Db::name('wy_houses_user_middle')->insert(['houses_id'=>$temp['houses_id'],'house_user_id'=>$arrid,'long'=>1,'middle_type'=>1]);
                                $lit[]=['houses_id'=>$temp['houses_id'],'house_user_id'=>$arrid,'long'=>1,'middle_type'=>1];
                            }else{
                                if($is_hased['houses_id']==0){
                                    $temp['id']=$is_hased['id'];
                                    $ret=$model->isUpdate(true)->save($temp);
                                }
                                $hasMid=Db::name('wy_houses_user_middle')
                                ->where('house_user_id',$is_hased['id'])
                                ->where('houses_id',$temp['houses_id'])
                                ->find();
                                if(!$hasMid){
                                    // Db::name('wy_houses_user_middle')->insert(['houses_id'=>$temp['houses_id'],'house_user_id'=>$is_hased['id'],'long'=>1,'middle_type'=>1]);
                                    $lit[]=['houses_id'=>$temp['houses_id'],'house_user_id'=>$is_hased['id'],'long'=>1,'middle_type'=>1];
                                }
                                
                            }
                        }
                    }
                }
                
                if(!$lit){
                        return ['code' => 1000, 'msg' => '共计'.($highestRow-1).'条数据,每页100条，当前'.$page.'/'.$toalPage, 'data' => ['page'=>$page]];
                }
                $ret=Db::name('wy_houses_user_middle')->insertAll($lit,true);
                if($ret){
                    return ['code' => 1000, 'msg' => '共计'.($highestRow-1).'条数据,每页100条，当前'.$page.'/'.$toalPage, 'data' => ['page'=>$page]];
                    
                }else {
                    return ['code' => 1, 'msg' => '导入错误,请重新导入！', 'data' => []];
                }
                break;
    }
    
}
function type_hao_user($bd_id,$type,$hao,$phone,$name){
    $has = Db::name('wy_house_user')->where('phone',$phone)->value('id');
    if ($has) {
        return $has;
    }
    $srr['bd_info_id'] = $bd_id;
    $srr['phone'] = $phone;
    $srr['gender'] = 3;
    $srr['name'] = $name;
    $srr['money'] = 0;
    $srr['status'] = 2;
    if (strstr($type,'车位')) {
        $tx = model('wy_car_area')->where(['name'=>$hao,'bd_info_id'=>$bd_id])->value('id');
    } elseif (strstr($type,'车牌') || strstr($type,'车辆')) {
        $tx = model('wy_car')->where(['name'=>$hao,'bd_info_id'=>$bd_id])->value('id');
    } else {
        $tx = model('wy_houses')->where(['name'=>$hao,'bd_info_id'=>$bd_id])->field('id,building_id,unit_id')->find();
        if ($tx) {
            $srr['building_id'] = $tx['building_id'];
            $srr['unit_id'] = $tx['unit_id'];
            $srr['houses_id'] = $tx['id'];
        }
    }
    if ($tx) {
        $uid = Db::name('wy_house_user')->insertGetId($srr);
        return $uid;
    } else {
        return false;
    }
}
function getUsertypeId($name){
    $arrs=['1'=>'业主本人','2'=>'亲属','3'=>'租客','4'=>'朋友','5'=>'同事','6'=>'保姆','7'=>'司机','8'=>'装修人员','9'=>'其它'];
    foreach($arrs as $k=>$v){
        if($v==$name){
            return $k;
        }
    }
    return 9;
}
/**
 * 判断字符串是否是日期格式
 * @param $date
 * @param $format
 * @return bool
 */
function is_date($date, $format = 'Y-m-d')
{
  if (!$date || $date == '0000-00-00') return false;
  $unix_time_1 = strtotime($date);
  if (!is_numeric($unix_time_1)) return false; //非数字格式
  $format_date = date($format, $unix_time_1);
  $unix_time_2 = strtotime($format_date);
  return ($unix_time_1 == $unix_time_2);
}

/**
 * excel数据导入  日期格式化
 * @param $date
 * @return false|string
 */
function get_date_by_excel($date)
{
  if (!$date || $date == '0000-00-00') return null;

  $unix_time = \PHPExcel_Shared_Date::ExcelToPHP($date);

  return ($unix_time < 0) ? date('Y-m-d', $unix_time) : date('Y-m-d', strtotime(gmdate('Y-m-d', $unix_time)));
}

/**
 * 获取excel日期格式化结果
 * @param $date string excel日期单元格字符串
 * @param $default string  $date未非日期时返回默认日期
 * @return string
 */
function excel_date_format($date, $default = '')
{
  if ($default == '') $default = date('Y-m-d');

  if (is_date($date)) return $date;

  return get_date_by_excel($date) ?: $default;
}